package net.angrynut.web.handler.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static net.angrynut.web.handler.AttributeNames.*;

/**
 * <p>
 * 这是一个 Spring MVC interceptor 示例。
 * 
 * <p>
 * 它尝试在日志中记录每一个请求的用时。
 *
 */
@Component
public class LogInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setAttribute(REQ_PERIOD_START, System.currentTimeMillis());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		double seconds = (System.currentTimeMillis() - (long) request.getAttribute(REQ_PERIOD_START)) / 1000.0;
		log.info("请求用时 " + seconds + "s");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// DO NOTHING
	}
}
